# coding=UTF-8
import os
import platform
import shutil
import subprocess
import sys
import time

from DingTalkUtil import DingTalkUtil
from OssUtils import OssUtil

sys.path.append(os.curdir + '/packageScript')
oss_url = "http://releasesdk.oss-cn-shenzhen.aliyuncs.com/packageApk/yi_yuan/"
oss_util = OssUtil()
ding_talk = DingTalkUtil()
branch_location = ""


def packing():
	clean_gradle()
	build_gradle()
	merge_apk()
	upload_apk()
	clear_apk()


def gradlew():
	sys = platform.system()
	if sys == "Windows":
		return "gradlew.bat "
	elif sys == "Linux":
		return "sudo ./gradlew "
		pass
	else:
		pass


def clean_gradle():
	execute(gradlew() + "clean")


def execute(cmd):
	print("当前运行指令=============>>" + cmd)
	os.system(cmd)


def build_gradle():
	argv = sys.argv[1:len(sys.argv)]
	if 'debug' in argv:
		change_branch('dev')
		print('debug')
		execute(gradlew() + "resguard_yyStaging")
	elif 'release' in argv:
		change_branch('release')
		print('release')
		execute(gradlew() + "assemble_yyRelease")
	else:
		print(argv)
		change_branch('release')
		for item in argv:
			execute(gradlew() + "assemble" + item + "Release")


def change_branch(branch):
	os.system("sudo git fetch")
	os.system("sudo git checkout -f origin/" + branch)
	os.system("sudo chmod -R 755 ./")
	global branch_location
	cmd = "sudo git branch --v"
	process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	result = process.stdout.read()
	branch_location = result.decode("utf-8")
	print("当前位置：" + result.decode("utf-8"))


def merge_apk():
	path = os.getcwd().replace("\\", "/") + "/app/build/outputs/apk/"
	apk_dir = os.getcwd().replace("\\", "/") + "/packing_apk"
	if not os.path.exists(apk_dir):
		os.mkdir(apk_dir)
	for file in os.listdir(path):
		if file == 'dev':
			continue
		if os.path.isdir(os.path.join(path, file)):
			channel_dir = os.path.join(path, file)
			for channelItem in os.listdir(channel_dir):
				channel_item_file = os.path.join(channel_dir, channelItem)
				for apkFile in os.listdir(channel_item_file):
					if apkFile.endswith('.apk'):
						shutil.move(os.path.join(channel_item_file, apkFile), apk_dir)
						print(os.path.join(channel_item_file, apkFile))


def upload_apk():
	apk_dir = os.getcwd().replace("\\", "/") + "/packing_apk/"
	timestamp = str(round(time.time() * 1000))
	message_content = ""
	for file in os.listdir(apk_dir):
		print("开始上传：" + file)
		try:
			result = oss_util.upload_file(timestamp, file, apk_dir + file)
			if result.status == 200:
				target_url = oss_url + timestamp + "/" + file
				print("上传成功：" + target_url)
				message_content += target_url + "\\n"
			else:
				message_content += file + "上传失败" + result.resp.response + "\\n"
				print("上传失败：" + result.resp.response)
		except Exception as e:
			message_content += file + "上传失败" + str(e) + "\\n"
			print("上传失败：" + str(e))
	current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(timestamp) / 1000))
	ding_talk_message = "【一元海外版】打包成功\\n 时间：" + current_time + "\\n分支位置：" + branch_location \
						+ "包链接：\\n" + message_content
	print("发送消息:" + ding_talk_message)
	ding_talk.send_text(ding_talk_message)


def clear_apk():
	apk_dir = os.getcwd().replace("\\", "/") + "/packing_apk"
	shutil.rmtree(apk_dir, ignore_errors=True)


if __name__ == "__main__":
	# change_branch("dev")
	if len(sys.argv) > 1:
		packing()
